package com.ruoyi.util;

import java.security.SecureRandom;
import java.util.ArrayList;

public class RandomStringGeneratorUtil {
    private static final String LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGITS = "0123456789";
    private static final String ALL_CHARACTERS = LOWERCASE_CHARACTERS + UPPERCASE_CHARACTERS + DIGITS;
    private static final SecureRandom RANDOM = new SecureRandom();

    public static String generateRandomString(int length) {
        StringBuilder randomString = new StringBuilder(length);

        // 确保至少包含一个小写字母、一个大写字母和一个数字字符
        randomString.append(LOWERCASE_CHARACTERS.charAt(RANDOM.nextInt(LOWERCASE_CHARACTERS.length())));
        randomString.append(UPPERCASE_CHARACTERS.charAt(RANDOM.nextInt(UPPERCASE_CHARACTERS.length())));
        randomString.append(DIGITS.charAt(RANDOM.nextInt(DIGITS.length())));

        // 生成剩余的字符
        for (int i = 3; i < length; i++) {
            randomString.append(ALL_CHARACTERS.charAt(RANDOM.nextInt(ALL_CHARACTERS.length())));
        }

        // 洗牌字符，使其顺序随机
        return shuffleString(randomString.toString());
    }

    // 函数用于洗牌字符串中的字符
    private static String shuffleString(String input) {
        char[] characters = input.toCharArray();
        for (int i = characters.length - 1; i > 0; i--) {
            int randomIndex = RANDOM.nextInt(i + 1);
            char temp = characters[i];
            characters[i] = characters[randomIndex];
            characters[randomIndex] = temp;
        }
        return new String(characters);
    }


}
